﻿//----------------------------------------------------------------------------
// Copyright (c) Pavel Tishkin 2012-2013.
//
// You must not remove this notice, or any other, from this software.
//----------------------------------------------------------------------------

namespace Lib.Dxp.Core

(*
    Serializer
        Json        - 
            load : string -> 'a
            save : 'a -> string

        ByteArray   - 
            load : byte[] -> 'a
            save : 'a -> byte[]

        ByteString  - 
            load : string -> 'a
            save : 'a -> string
*)

module Serializer =

    open System.IO
    open System.Runtime.Serialization
    open System.Runtime.Serialization.Json
    open System.Text



    module Json = 
    
        /// 'T -> Json string 
        let json<'t> (myObj:'t) =   
                use ms = new MemoryStream() 
                (new DataContractJsonSerializer(typeof<'t>)).WriteObject(ms, myObj) 
                Encoding.Default.GetString(ms.ToArray()) 
    
        /// Json string -> 'T
        let unjson<'t> (jsonString:string)  : 't =  
                use ms = new MemoryStream(ASCIIEncoding.Default.GetBytes(jsonString)) 
                let obj = (new DataContractJsonSerializer(typeof<'t>)).ReadObject(ms) 
                obj :?> 't

        let save x = json x
        let load x = unjson x


    module ByteArray = 
        let private bf = System.Runtime.Serialization.Formatters.Binary.BinaryFormatter()

        let save< 'a > (x : 'a) =
            use stream = new MemoryStream()
            bf.Serialize(stream, x)
            stream.ToArray() 

        let load< 'a >(xs : byte[]) : 'a = 
            use stream = new MemoryStream(xs)
            let f : 'a = unbox <| bf.Deserialize(stream)
            f
        

    module ByteString = 
        let save x = x |> ByteArray.save |> Json.save 
        let load x = x |> Json.load |> ByteArray.load

    